package mysql

import (
	"context"
	"errors"
	"shortUrl/models"
	"time"
)

type ServiceUrler interface{
	CreateShortUrl(ctx context.Context,req *models.Urls) error	
	FindShortUrl(ctx context.Context,shortCode string) (*models.Urls,error)
	DelateUrl() error
}
type ServiceUrl struct{

}
func NewServiceUrl()*ServiceUrl{
	return &ServiceUrl{}
}
func (s *ServiceUrl) CreateShortUrl(ctx context.Context,req *models.Urls) error {
	return DB.Create(req).Error
}	 
func (s *ServiceUrl) FindShortUrl(ctx context.Context,shortCode string) (*models.Urls,error) {
	var urls models.Urls
	if result := DB.Where(&models.Urls{ShortCode: shortCode}).First(&urls);result.RowsAffected == 0{
		return nil,errors.New("短链不存在")
	}
	return &urls,nil
}	 

func (s *ServiceUrl) DelateUrl() error{
	return DB.Where("expires_at < ?", time.Now().Unix()).Delete(&models.Urls{}).Error
}